import { genChartByAiUsingPost } from '@/services/yubi/chartController';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Card, Col, Divider, Form, Input, message, Row, Select, Space, Upload } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import React, { useState } from 'react';
import ReactECharts from 'echarts-for-react';

type SizeType = Parameters<typeof Form>[0]['size'];

const AddChart: React.FC = () => {
  const [componentSize, setComponentSize] = useState<SizeType | 'default'>('default');

  const onFormLayoutChange = ({ size }: { size: SizeType }) => {
    setComponentSize(size);
  };

  // 定义状态，用来接收后端的返回值，让它实时展示在页面上
  const [chart, setChart] = useState<API.BIResponse>();
  const [option, setOption] = useState<any>();
  // 提交中的状态，默认未提交
  const [submitting, setSubmitting] = useState<boolean>(false);

  /**
   * 提交
   * @param values
   */
  const onFinish = async (values: any) => {
    if (submitting) {
      // 如果正在提交，直接返回，避免重复提交
      return;
    }
    setSubmitting(true);
    //console.log('表单内容', values);
    //对接后端，上传数据
    const params = {
      ...values,
      file: undefined,
    };
    try {
      const res = await genChartByAiUsingPost(params, {}, values.file.file.originFileObj);
      console.log('表单内容', values);
      if (!res?.data) {
        message.error('分析失败');
      } else {
        setChart(res.data);
        message.success('分析成功');
        const chartOption = JSON.parse(res.data.genChart ?? '');
        console.log('图表代码', chartOption)
        if(!chartOption){
          throw new Error('图表代码解析错误')
        }
        setOption(chartOption);
      }
    } catch (e: any) {
      message.error('分析失败，' + e.message);
    }
    setSubmitting(false);
  };

  return (
    // 把页面内容指定一个类名add-chart
    <div className="add-chart">
      <Row gutter={24}>
        <Col span={12}>
          <Card title={'智能分析'}>
            <Form
              // 表单名称改为addChart
              name="addChart"
              onFinish={onFinish}
              // 初始化数据啥都不填，为空
              //initialValues={{}}
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 20 }}
              initialValues={{ size: componentSize }}
              onValuesChange={onFormLayoutChange}
              size={componentSize as SizeType}
              style={{ maxWidth: 600 }}
            >
              <Form.Item
                name="goal"
                label="分析目标"
                rules={[{ required: true, message: '请输入分析目标' }]}
              >
                <TextArea placeholder={'请输入你的分析需要，比如：分析网站用户的增长情况'} />
              </Form.Item>

              <Form.Item name="name" label="图表名称">
                <Input placeholder={'请输入你的图表名称，比如：网站流量分析图'} />
              </Form.Item>

              <Form.Item name="charType" label="图表类型">
                <Select
                  options={[
                    { value: '折线图', label: '折线图' },
                    { value: '柱状图', label: '柱状图' },
                    { value: '堆叠图', label: '堆叠图' },
                    { value: '饼图', label: '饼图' },
                    { value: '雷达图', label: '雷达图' },
                    { value: '任意图表', label: '任意图表'},
                  ]}
                ></Select>
              </Form.Item>

              <Form.Item name="file" label="原始数据">
                <Upload name="file">
                  <Button icon={<UploadOutlined />}>上传 excel 文件</Button>
                </Upload>
              </Form.Item>

              <Form.Item wrapperCol={{ span: 12, offset: 6 }}>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={submitting}
                    disabled={submitting}
                  >
                    智能分析
                  </Button>
                  <Button htmlType="reset">重置</Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Col>
        <Col span={12}>
          <Card title={'AI生成结果'}>
            <div>分析结论：{chart?.genResult}</div>
          </Card>
          <Divider />
          <Card title={'可视化图表/代码'}>
            <div>
              {/* 如果它存在，才渲染这个组件 */}

              {/*// 后端返回的代码是字符串，不是对象，用JSON.parse解析成对象*/}
              {option ? <ReactECharts option={option} /> : <div>
                {/*实在没办法了，就直接给代码：*/}
                <pre>
                <code className="javascript">
                  {chart?.genChart}
                </code>
              </pre>
              </div>}
              <Divider />
              <a
                href="https://echarts.apache.org/examples/zh/editor.html?c=line-simple"
                target="_blank"
              >
                <Button>点击跳转到生成图表的页面</Button>
              </a>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};
export default AddChart;
